<?php
/**
 * WB_S3EntityInfo class
 * 
 * @author Jean-Lou Dupont
 * @version @@package-version@@
 * @id $Id: S3EntityInfo.php 144 2008-03-14 18:57:42Z jldupont $
 */

 //{{include
 require_once 'web-bloks/AmazonS3/S3Base.php';
 //include}}
 
 abstract class WB_S3EntityInfo
 	extends WB_S3Base
 {
 	/**
 	 * Meta fields from body
 	 * @private
 	 */
 	static $fieldsBody = array();

 	/**
 	 * Meta fields from head
 	 * @private
 	 */
 	static $fieldsHead = array();
	
 	/**
 	 * Raw Object data from
 	 * the response body.
 	 */
 	var $raw = null;

	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%		
	// INTERNAL
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	abstract public function initFromRaw( &$raw );
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%		
	// INTERNAL
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	/**
	 * init
	 * 
	 * @return void
	 * @param $raw string
	 */			
	protected function init( $raw, $fieldsHead, $fieldsBody )
	{
		$this->raw = $raw;

		if ( !is_null( $fieldsHead ))
			$this->extractFromHead( $fieldsHead );		

		if ( !is_null( $fieldsBody ))
			$this->extractFromBody( $fieldsBody );
	
	}
	protected function extractFromHead( &$fieldsHead )
	{
		$liste = explode( "\n", $this->raw );

		if (empty( $liste ))
			return;

		foreach( $liste as $line )
		{
			$bits = explode( ':', $line );
			$key = trim( $bits[0] );
			$keyLC = strtolower( $key );
			$value = $bits[1];
		
			// known fields?	
			if ( in_array( $keyLC, $fieldsHead ))
				$this->liste[ $key ] = trim( $value );
			
			// meta?
			if ( strpos( $keyLC, 'x-amz-meta-' ) !== false)
				$this->liste[ $key ] = trim( $value );				
		}
	}
	protected function extractFromBody( &$fieldsBody )
	{
		foreach( $fieldsBody as $key )	
		{
			$value = $this->extractKeyFromBody( $key );
			if ( !is_null( $value ))
				$this->liste[ $key ] = trim( $value );
		}
	}	
	protected function extractKeyFromBody( &$key )
	{
		if ( empty( $this->raw ) )
			return null;
		
		// make sure to keep case-insensitive processing!
		$r = preg_match("/\<"."${key}\>(.*?)\<\/${key}\>/i", $this->raw, $match);
		if (($r === false) || ($r === 0))
			return null;
			
		return $match[1];
	}
	
 } // end class declaration
 